'use client'
import React, { useState, useEffect, useRef } from 'react';
import { AudioOutlined, PoweroffOutlined } from '@ant-design/icons';
import { message } from 'antd'
import './index.scss';
import KeyStore from '@/app/store/key';

interface SoundRecordingProps {
    onSend: (text: string) => void;
}

const SoundRecording: React.FC<SoundRecordingProps> = ({ onSend }) => {

    const [isVoice, setisVoice] = useState<boolean>(true);
    const [isVoiceTime, setisVoiceTime] = useState<string>('00:00');
    const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);

    const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
    const mediaRecorderRef = useRef<MediaRecorder | null>(null);
    const streamRef = useRef<MediaStream | null>(null);
    const key = KeyStore((state) => state.key)

    useEffect(() => {
        if (!isVoice) {
            const interval = setInterval(() => {
                const [minutes, seconds] = isVoiceTime.split(':').map(Number);
                if (seconds < 59) {
                    setisVoiceTime(`${minutes.toString().padStart(2, '0')}:${(seconds + 1).toString().padStart(2, '0')}`);
                } else if (minutes < 59) {
                    setisVoiceTime(`${(minutes + 1).toString().padStart(2, '0')}:00`);
                } else {
                    clearInterval(interval);
                    setTimer(null);
                }
            }, 1000);
            setTimer(interval);
        }
        return () => {
            if (timer) {
                clearInterval(timer);
            }
        };
    }, [isVoice, isVoiceTime]);

    const startRecording = async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            streamRef.current = stream;
            const recorder = new MediaRecorder(stream);
            mediaRecorderRef.current = recorder;
            recorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    setAudioBlob(event.data);
                }
            };

            // 录音停止开始触发
            recorder.onstop = () => {
                streamRef.current?.getTracks().forEach(track => track.stop());
            };
            recorder.start();
            setisVoice(false);
        } catch (error) {
            message.error('无法获取麦克风权限，请在浏览器设置中允许访问麦克风。');
        }
    };

    const stopRecording = () => {
        if (mediaRecorderRef.current) {
            mediaRecorderRef.current.stop();
        }
    };

    const sendAudioToServer = async () => {
        if (!audioBlob) {
            message.error('没有录制的音频');
            return;
        }

        const formData = new FormData();
        formData.append('file', audioBlob, 'audio.webm');

        fetch(`${process.env.NEXT_PUBLIC_API_URL_ALIAS}/audio-to-text`, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${key}`
            },
            body: formData,
        }).then(res => res.json()).then(res => {
            const str = res.text.replace(/[\u{1F600}-\u{1F64F}|\u{1F300}-\u{1F5FF}|\u{1F680}-\u{1F6FF}|\u{1F1E0}-\u{1F1FF}|\u{2694}-\u{2697}|\u{2699}-\u{269F}|\u{2600}-\u{26FF}|\u{2700}-\u{27BF}]/gu, '');
            onSend(str)
        })

    };

    const handleStartRecord = async () => {
        await startRecording();
    };

    const handleStopRecord = () => {
        stopRecording();
        sendAudioToServer();
    };

    return (
        <div className='SoundRecording' onClick={() => {
            if (isVoice) {
                setisVoiceTime('00:00');
                handleStartRecord()
            } else {
                handleStopRecord()
                setisVoice(true)
            }

        }}>
            {
                isVoice ? <AudioOutlined />
                    : <div className='close'>
                        <PoweroffOutlined /><span className='voiceTime'>
                            {isVoiceTime}
                        </span>
                    </div>
            }
        </div>
    )
}

export default SoundRecording